<template>
  <div class="policy-container">
    <el-card shadow="hover" class="policy-card">
      <template #header>
        <div class="card-header">
          <span class="title">助农政策</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增政策
          </el-button>
        </div>
      </template>

      <el-table :data="policiesList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="政策标题" width="250" />
        <el-table-column prop="content" label="政策内容" width="300" :show-overflow-tooltip="true" />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column prop="source" label="来源" width="150" />
        <el-table-column prop="viewCount" label="浏览次数" width="100" />
        <el-table-column label="操作" width="150">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogVisible" :title="policyForm.id ? '编辑助农政策' : '新增助农政策'" width="60%">
        <el-form :model="policyForm" :rules="rules" ref="policyFormRef" label-width="100px">
          <el-form-item label="政策标题" prop="title">
            <el-input v-model="policyForm.title" placeholder="请输入政策标题" clearable />
          </el-form-item>
          <el-form-item label="政策内容" prop="content">
            <el-input v-model="policyForm.content" type="textarea" placeholder="请输入政策内容" clearable rows="8" />
          </el-form-item>
          <el-form-item label="政策视频">
            <el-upload
                class="file-uploader"
                :show-file-list="false"
                :before-upload="beforeVideoUpload"
                :http-request="uploadVideo"
            >
              <div class="file-wrapper">
                <video v-if="isVideoFile(policyForm.video)" :src="policyForm.video" controls class="file-image" />
                <img v-else-if="policyForm.video" :src="policyForm.video" class="file-image" />
                <div v-else class="file-placeholder">
                  <el-icon class="upload-icon"><VideoPlay /></el-icon>
                  <span class="upload-text">上传政策视频</span>
                </div>
                <div v-if="policyForm.video" class="file-info">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ getFileName(policyForm.video) }}</span>
                  <el-button link type="danger" @click.stop="policyForm.video = ''">删除</el-button>
                </div>
              </div>
              <div class="mt-2 text-sm text-gray-500">支持MP4格式，大小不超过50MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="政策附件">
            <el-upload
                class="file-uploader"
                :show-file-list="false"
                :before-upload="beforeAttachmentUpload"
                :http-request="uploadAttachment"
            >
              <div class="file-wrapper">
                <img v-if="isImageFile(policyForm.attachment)" :src="policyForm.attachment" class="file-image" />
                <video v-else-if="isVideoFile(policyForm.attachment)" :src="policyForm.attachment" controls class="file-image" />
                <div v-else-if="policyForm.attachment" class="file-preview-placeholder">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <span class="file-name">{{ getFileName(policyForm.attachment) }}</span>
                </div>
                <div v-else class="file-placeholder">
                  <el-icon class="upload-icon"><File /></el-icon>
                  <span class="upload-text">上传政策附件</span>
                </div>
                <div v-if="policyForm.attachment" class="file-info">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ getFileName(policyForm.attachment) }}</span>
                  <el-button link type="danger" @click.stop="policyForm.attachment = ''">删除</el-button>
                </div>
              </div>
              <div class="mt-2 text-sm text-gray-500">支持任何格式，大小不超过100MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
                v-model="policyForm.publishTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-input v-model="policyForm.source" placeholder="请输入来源" clearable />
          </el-form-item>
          <el-form-item label="浏览次数" prop="viewCount">
            <el-input-number v-model="policyForm.viewCount" :min="0" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus, Edit, Delete, VideoPlay, File, Document } from '@element-plus/icons-vue'

const policiesList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const policyForm = ref({
  id: null,
  title: '',
  content: '',
  video: null,
  attachment: null,
  publishTime: '',
  source: '',
  viewCount: 0
})
const rules = {
  title: [
    { required: true, message: '政策标题不能为空', trigger: 'blur' },
    { min: 3, max: 100, message: '长度在3到100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '政策内容不能为空', trigger: 'blur' }
  ],
  publishTime: [
    { required: true, message: '发布时间不能为空', trigger: 'change' }
  ],
  source: [
    { required: true, message: '来源不能为空', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在1到100个字符', trigger: 'blur' }
  ],
  viewCount: [
    { type: 'number', min: 0, message: '浏览次数必须大于等于0', trigger: 'blur' }
  ]
}
const policyFormRef = ref(null)

// 从localStorage获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 视频上传前校验
const beforeVideoUpload = (file) => {
  const isVideo = file.type === 'video/mp4';
  const isLt50M = file.size / 1024 / 1024 < 500;

  if (!isVideo) {
    ElMessage.error('只能上传MP4格式的视频!');
    return false;
  }
  if (!isLt50M) {
    ElMessage.error('视频大小不能超过500MB!');
    return false;
  }

  return true;
};

// 视频上传
const uploadVideo = async (options) => {
  const { file } = options;
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('视频上传成功');
      policyForm.value.video = response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('视频上传出错：' + error.message);
    throw error;
  }
};

// 附件上传前校验
const beforeAttachmentUpload = (file) => {
  const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isLt100M) {
    ElMessage.error('附件大小不能超过100MB!');
    return false;
  }

  return true;
};

// 附件上传
const uploadAttachment = async (options) => {
  const { file } = options;
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('附件上传成功');
      policyForm.value.attachment = response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('附件上传出错：' + error.message);
    throw error;
  }
};

// 辅助函数：判断是否为视频文件
const isVideoFile = (url) => {
  if (!url) return false;
  const videoExtensions = ['.mp4', '.webm', '.ogg'];
  return videoExtensions.some(ext => url.toLowerCase().endsWith(ext));
};

// 辅助函数：判断是否为图片文件
const isImageFile = (url) => {
  if (!url) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  return imageExtensions.some(ext => url.toLowerCase().endsWith(ext));
};

// 辅助函数：获取文件名
const getFileName = (url) => {
  if (!url) return '';
  return url.split('/').pop() || '未知文件';
};

const fetchPolicies = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${BASE_URL}/api/v1/government/public/get`)
    policiesList.value = response.data.data
  } catch (error) {
    console.error('获取助农政策失败:', error)
    ElMessage.error('获取助农政策失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  policyForm.value = {
    id: null,
    title: '',
    content: '',
    video: null,
    attachment: null,
    publishTime: new Date().toISOString().slice(0, 16),
    source: '',
    viewCount: 0
  }
  dialogVisible.value = true
}

const handleEdit = (rowData) => {
  policyForm.value = {
    ...rowData,
    publishTime: rowData.publishTime ? new Date(rowData.publishTime).toISOString().slice(0, 16) : ''
  }
  dialogVisible.value = true
}

const handleDelete = async (rowData) => {
  console.log("政策id:"+rowData.id)
  if (confirm('确定要删除该条政策吗？')){
    axios.post(BASE_URL+'/api/v1/government/private/deletePolicy', null, {
      params: { id: rowData.id }
    }).then((response)=>{
      if(response.data.code == 2000){
        ElMessage.success('删除成功')
        fetchPolicies()
      }else{
        ElMessage.error('删除失败')
      }
    })
  }
}

const submitForm = async () => {
  try {
    await policyFormRef.value.validate()
    const payload = {
      ...policyForm.value,
      video: policyForm.value.video || '',
      attachment: policyForm.value.attachment || ''
    }

    let response
    if (payload.id) {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/updatePolicy`, payload)
    } else {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/set`, payload)
    }

    if (response.data.code == 2000) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchPolicies()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存助农政策失败:', error)
      ElMessage.error('保存助农政策失败')
    }
  }
}

onMounted(() => {
  fetchPolicies()
})
</script>

<style scoped>
.policy-container {
  margin: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.policy-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.file-uploader {
  --el-avatar-size: 178px;
  width: 100%;
}

.file-wrapper {
  position: relative;
  width: 100%;
  min-height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.file-wrapper:hover {
  border-color: var(--el-color-primary);
}

.file-image {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
}

.file-preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
  padding: 20px;
}

.file-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.file-info {
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-name {
  margin: 0 10px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: #8c939d;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table::before {
  background-color: transparent;
}

.el-dialog__header {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.el-dialog__footer {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}
</style>